<?php
//命名空间声明
namespace Admin\Controller;
//引入父类控制器
use Think\Controller;
//声明类并且继承父类
class UserController extends BaseController{
	public function add(){
		if(IS_POST){
			$model=M('User');
			$data=$model->create();
			$data['addtime']=time();
			$result=$model->add($data);
			if($result){
				$this->success('添加成功',U('showList'),3);
			}else{
				$this->error('添加失败');
			}
		}else{
			$model=M('Dept');
			$data=$model->field('id,name')->select();
			$this->assign('data',$data);
			$this->display();
		}
	}
	public function showList(){
		$model=M('User');
		//方法一
		// foreach($data as $key=>$value){
		// 	$info=M('Dept')->find($value['dept_id']);
		// 	$data[$key]['deptname']=$info['name'];
		// }
		$count=$model->count(); 
		$page=new \Think\Page($count,2);
		$page->setConfig('prev','上一页');
		$page->setConfig('next','下一页');
		$page->setConfig('last','末页');
		$page->setConfig('first','首页');
		$show=$page->show();
		//方法二 table方法
		//sql:select t1.*,t2.name as deptname from oa_user as t1,oa_dept as t2 where t1.dept_id=t2.id
		//select t1.*,t2.name as deptname form oa_dept as t1 left join oa_dept as t2 on t1.pid=t2.id;
		$data=$model->field('t1.*,t2.name as deptname')->table('oa_user as t1,oa_dept as t2')->where('t1.dept_id=t2.id')->limit($page->firstRow,$page->listRows)->select();
		$this->assign('data',$data);
		$this->assign('show',$show);
		$this->display();
	}
	public function edit(){
		if(IS_POST){
			$post=I('post.');
			$model=M('User');
			$result=$model->save($post);
			if ($result !== false) {
				$this->success('修改成功',U('showList'),3);
			}else{
				$this->error('修改失败');
			}
		}else{
			$id=I('get.id');
			$model=M('User');
			$model2=M('Dept');
			$data=$model->find($id);
			$data2=$model2->select();
			$this->assign('data',$data);
			$this->assign('data2',$data2);
			$this->display();
		}
	}
	public function del(){
		$id=I('get.id');
		$model=M('User');
		$result=$model->delete($id);
		if($result){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}
	public function charts(){
		//oa_user 关联 oa_dept t1.dept_id=t2.id
		// select t2.name as deptname,count(*) as count from oa_user as t1,oa_dept as t2 where t1.dept_id=t2.id group by deptname;
		$model=M();
		$data=$model->field('t2.name as deptname,count(*) as count')->table('oa_user as t1,oa_dept as t2')->where('t1.dept_id=t2.id')->group('deptname')->select();
		$str='[';
		$count='[';
		foreach ($data as $key => $value) {
			$str.="'" . $value['deptname'] . "'" . ",";
			$count.="'" . $value['count'] . "'" . ",";
		}
		//去除最后的逗号
		$str=rtrim($str,',') . ']';
		$count=rtrim($count,',') . ']';
		$this->assign('str',$str);
		$this->assign('count',$count);
		$this->display();
	}
}